import 'dart:convert';
import 'dart:ffi';
import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:gw_github_flutter/models/repo.dart';
import 'package:gw_github_flutter/models/user.dart';

import 'global.dart';

class GwNet {
  BuildContext? context;
  late Options _options;
  GwNet([this.context]) {
    _options = Options(extra: {"context": context});
  }
  static Dio dio = new Dio(BaseOptions(
    baseUrl: 'https://wxmini.baixingliangfan.cn/baixing/',
    headers: {
      HttpHeaders.acceptHeader: "application/vnd.github.squirrel-girl-preview,"
          "application/vnd.github.symmetra-preview+json",
    },
  ));

  static init() {
    // 添加缓存插件
    dio.interceptors.add(Global.netCache);
    // 设置用户token（可能为null，代表未登录）
    dio.options.headers[HttpHeaders.authorizationHeader] = Global.profile.token;

    // 在调试模式下需要抓包调试，所以我们使用代理，并禁用HTTPS证书校验
    if (!Global.isRelease) {
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        // client.findProxy = (uri) {
        //   return 'PROXY 192.168.50.154:8888';
        // };
        //代理工具会提供一个抓包的自签名证书，会通不过证书校验，所以我们禁用证书校验
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
      };
    }
  }

  // 登录接口，登录成功后返回用户信息
  Future<User> login(String login, String pwd) async {
    String basic = 'Basic ' + base64.encode(utf8.encode('$login:$pwd'));
    var res = await dio.get('/user',
        options: _options.copyWith(headers: {
          HttpHeaders.authorizationHeader: basic
        }, extra: {
          Global.gwRequestStateNoCache: true,
        }));
    //登录成功后更新公共头（authorization），此后的所有请求都会带上用户身份信息
    dio.options.headers[HttpHeaders.authorizationHeader] = basic;
    //清空所有缓存
    Global.netCache.cache.clear();
    //更新profile中的token信息
    Global.profile.token = basic;
    return User.fromJson(res.data);
  }

  Future<List<Repo>> getRepos(
      {Map<String, dynamic>? queryParameters, refrash = false}) async {
    if (refrash) {
      // 列表下拉刷新，需要删除缓存（拦截器中会读取这些信息）
      _options.extra?.addAll({"refresh": true, "list": true});
    }
    var res = await dio.get<List>('user/repos',
        queryParameters: queryParameters, options: _options);
    return res.data?.map((e)=>Repo.fromJson(e)).toList() ?? [];
  }
}
